<?php

/**
 * CelebrioPeople default
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    CelebrioPeople
 */
namespace ApplicationsModule\PeopleModule;

use WebtopModule\BasePresenter;

use Nette\Environment;
use Nette\Forms\Form;
use Nette\Application\AppForm;
use \Nette\ArrayTools;

use Celebrio\Modules;
use Celebrio\Core\ServiceProvider;
use \Celebrio\Core\NoSuchServiceException;


class DefaultPresenter extends BasePresenter {

    /** @var ApplicationsModule\PeopleModule\PeopleManagement */
    private $peopleManager;

    /** @var int */
    private $user_id;

    /** @var array(ApplicationsModule\PeopleModule\IContactService) */
    private $contact_modules;

    public function __construct() {
        parent::__construct();
        $this->peopleManager = ServiceProvider::getService(Modules::PEOPLE);
        $this->user_id = $this->getUser()->getIdentity()->id;

        $this->contact_modules = ServiceProvider::getAllServices(Modules::CONTACTS);
    }

    // --------------
    // render methods
    // --------------
    
    public function renderDefault() {

        $this->getTemplate()->title = _("People");

        $userId = $this->getUser()->getIdentity()->id;
        $this->getTemplate()->friends = $this->peopleManager->getFriends($userId);
    }

    public function renderNew() {
        $this->getTemplate()->contact_items = PeopleItems::info_items();
        $this->getTemplate()->title = _("Connect with other people");
    }

    public function renderDetail($id) {
        $person = $this->peopleManager->getPerson($id);
        $this->getTemplate()->person = $person;
        $this->getTemplate()->mail_addresses = ArrayTools::get($person->getAdditionalInfo(), "mail_address", array());

        $this['newMailForm']['person_id']->setDefaultValue($id);
    }


    //------------
    // components
    //------------

    protected function createComponentNewMailForm() {
        $form = new AppForm();

        $form->addText("e_mail", _("E-mail"))
                ->addRule(Form::EMAIL)
                ->addRule(Form::FILLED, _("Please, enter valid e-mail address."))
        ->controlPrototype->type("mail");
        $form->addHidden("person_id");

        $form->addSubmit('save', _('Save'));
        $form->onSubmit[] = callback($this, 'newMailFormSubmitted');

        return $form;
    }

    public function newMailFormSubmitted($form) {
        $values = $form->values;
        $mail = $values["e_mail"];
        $personId = $values["person_id"];

        if ($this->peopleManager->addMail($personId, $mail)) {
            $this->flashMessage(sprintf(_("Mail address %s successfully added."), $mail));
        } else {
            $this->flashMessage(sprintf(_("Mail address %s had already been assigned before, no change."), $mail));
        }


        $this->redirect("default");
    }

    protected function createComponentNewUserForm() {
        $form = new AppForm();

        $form_contact_providers = $this->contact_modules;
        array_unshift($form_contact_providers, PeopleItems::getReflection()->name);
        
        foreach ($form_contact_providers as $contact_provider) {
            foreach ($contact_provider::providedRows(array()) as $row) {
                if ($row['display'] !== false) {
                    if (isset($row["type"]) && $row["type"] === "file") {
                        $input = $form->addFile($row['db'], $row['display']);
                    } else {
                        $input = $form->addText($row['db'], $row['display']);
                    }
                } else {
                    $input = $form->addHidden($row['db'], $row['display']);
                }
                $input->htmlId = $row['db'];
                $input->getControlPrototype()->addClass("person_field");
            }
        }

        $form->addSubmit('save', _('Save'))->htmlId = "save";

        $form->onSubmit[] = callback($this, 'createUser');
        return $form;
    }


    // signals (37)
    // ------------

    public function handleSearch($info) {
        $this->getTemplate()->contacts = array();
        $existing_users = $this->peopleManager->searchExisting($info);
        $this->getTemplate()->contacts["existing"] = $existing_users;

        $any_results = !empty($existing_users);

        foreach ($this->contact_modules as $contact_provider) {
            $search_result = $contact_provider->search($info);
            if ($search_result !== DummyContactService::NOT_PROVIDED) {
                if (!empty($search_result)) {
                    $any_results = true;
                    $this->getTemplate()->contacts[$contact_provider::getServiceName()] = $search_result;
                }
            }
        }

        if ($any_results) {
            $this->invalidateControl("pictures");
        }
    }

    public function createUser(AppForm $form) {
        
        $values = $form->getValues();
        $person = Person::fromValues($values);

        $this->peopleManager->createPerson($person);
        $this->flashMessage(sprintf(_("The contact %s %s was successfully created and you are connected now."),
                $person->getFirstName(), $person->getLastName()));
        $this->redirect("default");
    }

}